package com.lqq.util;

import cn.zhxu.okhttps.HTTP;
import cn.zhxu.okhttps.fastjson2.Fastjson2MsgConvertor;
import com.lqq.domain.response.BaseResponse;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.swing.*;
import java.io.IOException;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;

public class HttpUtil {


  private static CookieJar myCookieJar = new CookieJar() {

    private HashMap<String, List<Cookie>> cookieMap = new HashMap<>();

    @Override
    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
      //保证 登录时的sessionId 和获取验证码返回的sessionId 相同 否则无法验证验证码
      cookieMap.put("captcha", cookies);
    }

    @Override
    public List<Cookie> loadForRequest(HttpUrl url) {

      return cookieMap.getOrDefault("captcha", new ArrayList<>());
    }

  };

  public static HTTP INSTANCE = HTTP.builder()
      .config(b -> {
        b.cookieJar(myCookieJar);
      })
      .baseUrl("http://210.45.195.32/prod-api")
      .addMsgConvertor(new Fastjson2MsgConvertor())
      .build();

  public static BaseResponse post(String url, Object request) throws IOException {

    BaseResponse baseResponse = INSTANCE.sync(url)
        .bodyType("json")
        .setBodyPara(request)
        .addHeader("appid", "h5ebe58fe7ef505d07")
        .addHeader("appPlatformType", "3")
        .addHeader("loginType", "CUSTOMER")
        .addHeader("tenant", "tenant1")
        .post()
        .getBody()
        .toBean(BaseResponse.class);

    return afterRequest(baseResponse);
  }

  public static BaseResponse post(String url) throws IOException {
    return post(url, null);
  }

  public static BaseResponse get(String url) throws IOException {
    return get(url, null);
  }

  public static BaseResponse afterRequest(BaseResponse baseResponse) {
    Integer code = baseResponse.getCode();
    if (code == 0 || code == 200) {
      return baseResponse;

    } else {
      //TODO 弹窗提示
      System.out.println(baseResponse.getMsg());
      String msg = baseResponse.getMsg();

      if (msg.equals("null")) {
        msg = "系统异常";
      }
      JOptionPane.showMessageDialog(null, msg, "系统提示", JOptionPane.WARNING_MESSAGE);
      throw new RuntimeException("系统异常");
    }

  }


  public static BaseResponse get(String url, Object request) throws IOException {

    BaseResponse baseResponse = INSTANCE.sync(url)
        .setBodyPara(request)
        .addHeader("loginType", "CUSTOMER")
        .addHeader("tenant", "tenant1")
        .get()
        .getBody()
        .toBean(BaseResponse.class);
    System.out.println(baseResponse);
    return afterRequest(baseResponse);
  }

}
